<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\Department;
use yii\db\Query;
use yii\db\Command;
use yii\data\Pagination;
use yii\helpers\Url;

class DepartmentController extends \app\base\Controller
{
    //部门列表
    public function actionIndex()
    {
        $model       = new Department();
        $admin_ses   = Yii::$app->session['admin_info'];
        if ($admin_ses['powers'] == 'all') {
            $res = $model->getDpt_list();
        } else {
            $res = $model->getDpt_list($admin_ses['department_id']);
        }
        $sel_html = $model->made_list_html($res);
        return $this->render('index', ['sel_html' => $sel_html]);
    }

    public function actionAdd()
    {
       
        $model = new Department();
        $admin_ses = Yii::$app->session['admin_info'];
        if ($admin_ses['powers'] != 'all' && $admin_ses['is_owner'] != 1) { //即不是管理员，也不是部门负责人，不能修改部门数据
            $this->sysMsg('提示', '当前账号暂时无权限!', $params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页', 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        if ($model->load(Yii::$app->request->post()) && $model->saveDeaprtment()) {
           
            $rtn_url    = Url::toRoute(['department/']);
            return $this->sysMsg('提示', '添加成功',$params = [ 'type' => 'success', 'links' => [ ['name'=>'返回部门列表', 'url'=>$rtn_url] ] ]);
        }
        
        if ($admin_ses['powers'] == 'all') {
            $res        = $model->getDpt_list();
            $sel_arr    = array(array('id'=>0,'de_name'=>'顶级分类','parent_id'=>0));
            $res        = array_merge($sel_arr,$res);
        } else {
            $res = $model->getDpt_list($admin_ses['department_id']);
        }
        $sel_html = $model->made_select($res);
        $csrf = Yii::$app->request->getCsrfToken();
        return $this->render('add', ['model'=>$model,'dpart_list_html'=>$sel_html, 'csrf'=>$csrf]);
    }
    
    public function actionUpdate()
    {
        $model      = new Department(); 
        $up_id      = yii::$app->request->get('up_id');
        $up_id      = intval($up_id);
        $admin_ses  = Yii::$app->session['admin_info'];
        
        // 模块id相关
        $module_id1 = Yii::$app->params['sites']['sys_email']['module_id'];
        $module_id2 = Yii::$app->params['sites']['marketing_email']['module_id'];
        $module_id3 = Yii::$app->params['sites']['sys_set']['module_id'];
        
        if($admin_ses['powers'] != 'all' && $admin_ses['is_owner'] != 1 ) { //即不是管理员，也不是部门负责人，不能修改部门数据
            $this->sysMsg('提示', '当前账号暂时无权限!', $params = [ 'type' => 'warning', 'links' => [ ['name'=>'返回上一页', 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        if($admin_ses['powers'] != 'all' && $up_id == $admin_ses['department_id']) { //自己不能修改自己的部门,只有上级或管理员才能修改本部门的权限
            $this->sysMsg('提示', '你不能修改自己的部门,只能修改自己部门的人员和下级部门或下次部门的人员!', $params = [ 'type' => 'warning', 'links' => [ ['name'=>'返回上一页', 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $update_info = [];
        
        if ($model->load(Yii::$app->request->post()) && $update_info = $model->updateDepartment()) {
            $rtn_url    = Url::toRoute(['department/']);
            if (!empty($update_info['change_arr'])) {
                 $this->sysMsg('提示', '修改成功!',$params = [ 'type' => 'success', 'links' => [['name'=>'返回部门列表', 'url'=>$rtn_url] ]]);
            } else {
                $this->sysMsg('提示', '没有进行任何更改!',$params = [ 'type' => 'success', 'links' => [['name'=>'返回部门列表', 'url'=>$rtn_url] ]]);
            } 
        }
        $up_data = $model->get_dpar_info($up_id);
        $powers_tmp = [];   // 权限节点数组
        $powers_tmp = explode(',',$up_data['powers']);
       
        
        // 权限节点相关
        $up_data['powers1'] = '';
        $powers1_tmp = [];
        
        $up_data['powers2'] = '';
        $powers2_tmp = [];
        
        $up_data['powers3'] = '';
        $powers3_tmp = [];
        
        foreach ($powers_tmp as $powers_tmp_k => $powers_tmp_v) {
            if (strpos($powers_tmp_v,$module_id1.'-') !== false) {
                $powers1_tmp[] = explode('-',$powers_tmp_v)[1];
            }
            
            if (strpos($powers_tmp_v,$module_id2.'-') !== false) {
                $powers2_tmp[] = explode('-',$powers_tmp_v)[1];
            }
            
            if (strpos($powers_tmp_v,$module_id3.'-') !== false) {
                $powers3_tmp[] = explode('-',$powers_tmp_v)[1];
            }
        }
        
        $up_data['powers1'] = join(',',$powers1_tmp);
        $up_data['powers2'] = join(',',$powers2_tmp);
        $up_data['powers3'] = join(',',$powers3_tmp);
       
        
        
        if (!$up_data) {
            $this->sysMsg('提示', '数据不存在!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页', 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        if ($admin_ses['powers'] == 'all') {
            $res        = $model->getDpt_list();
            $sel_arr    = array(array('id'=>0, 'de_name'=>'顶级分类', 'parent_id'=>0));
            $res        = array_merge($sel_arr, $res);
        } else {
            $res = $model->getDpt_list($admin_ses['department_id']);
        }
        $sel_html   = $model->made_select($res, '', 0, $up_data['parent_id']);
        $parent_id  = intval($up_data['parent_id']) > 0 ? intval($up_data['parent_id']) : 0;
       
        $pow_list   = $model->get_powers_list($parent_id);
        //echo '<pre>';
        //print_R($pow_list);
        $par_web1 = $pow_list['web_list1'];
        $par_web2 = $pow_list['web_list2'];
        //var_dump($par_web1);
        //exit;
        //$par_web1    = Yii::$app->params['sites'][''];
        //$par_web2    = Yii::$app->params['sites'][''];
        if ($parent_id > 0) {
           
            $parent_info    = $model->get_dpar_info($parent_id);
            $alw_web        = $parent_info['allow_web']; //父类允许的网站
           
        }
       
        $web_list1 = array();
        $web_list2 = array();
        //echo '<pre>';
       // print_R($par_web);
       // exit;
       
        if($par_web1){
            // 系统邮件相关的网站
            foreach ($par_web1 as $k=>$v) {
                //if ($k != 'sys_set') {
                    if (isset($alw_web)) {

                        if (strpos($alw_web, $module_id1.'-'.$v['value']) !== false) {
                            $web_list1[$k] = $v;  
                        }
                    } else {

                        $web_list1[$k] = $v;
                    } 

               // } 

            }
        }
        if($par_web2)
        {
            // 营销邮件相关的网站
            foreach ($par_web2 as $k=>$v) {
               // if ($k != 'sys_set') {
                    if (isset($alw_web)) {
                        if (strpos($alw_web, $module_id2.'-'.$v['value']) !== false) {
                            $web_list2[$k] = $v;  
                        }
                    } else {
                        $web_list2[$k] = $v;
                    } 
                //}
            }
        }
        
        
        $csrf = Yii::$app->request->getCsrfToken();
        
        return $this->render('update', [
            'model'             => $model,
            'dpart_list_html'   => $sel_html,
            'csrf'              => $csrf,
            'up_data'           => $up_data,
            'pow_list1'          => $pow_list['pow_list'][1],
            'pow_list2'          => $pow_list['pow_list'][2],
            'pow_list3'          => $pow_list['pow_list'][3],
            //'web_list'          => $web_list
            'web_list1'         => $web_list1,
            'module_id1'        => $module_id1, 
            'module_id2'        => $module_id2, 
            'web_list2'          => $web_list2,
        ]);
    }
    
    public function actionAjaxdata()
    {
        $par_id = Yii::$app->request->get('department');
        if ($par_id == '') {
            $rtn_arr['status']  = 1;
            $rtn_arr['msg']     = 'ok';
            $rtn_arr['pubs']    = '';
            echo json_encode($rtn_arr);
            exit;
        }
        $model      = new Department(); 
        $res        = $model->get_powers_list($par_id);
       
        $rtn_arr    = array('status'=>0,'msg'=>'失败');
        if ($res) {
            $rtn_arr['status']  = 1;
            $rtn_arr['msg']     = 'ok';
           
            // 系统邮件
            $rtn_arr['pubs1'] = isset($res['pow_list'][1]['menu_list']) ? $res['pow_list'][1]['menu_list'] : [];
            $rtn_arr['pubs2'] = isset($res['pow_list'][2]['menu_list']) ? $res['pow_list'][2]['menu_list'] : [];
            $rtn_arr['pubs3'] = isset($res['pow_list'][3]['menu_list']) ? $res['pow_list'][3]['menu_list'] : [];
            // $rtn_arr['pubs']    = $res['pow_list'];
            $rtn_arr['web']     = $res['web_list'];
            $rtn_arr['web1']     = $res['web_list1'];
            $rtn_arr['web2']     = $res['web_list2'];
        }
        echo json_encode($rtn_arr);
        exit;
    }
    
    public function actionDel()
    {
        $del_id     = Yii::$app->request->get('del_id');
        $del_id     = intval($del_id);
        $rtn_arr    = [];
        if ($del_id =='' || $del_id == 0) {
            $rtn_arr['_state']  = 'error';
            $rtn_arr['_msg']    = '数据有误';
            echo json_encode($rtn_arr);
            exit;
        }
        
        $model      = new Department(); 
        $del_dat    = $model->findOne($del_id);
        if(!$del_dat)
        {
            $rtn_arr['_state']  = 'ok';
            $rtn_arr['_msg']    = '删除成功!';
            echo json_encode($rtn_arr);
            return ;
        }
        $res = $model->get_part_low_list($del_id, 2);
        if (count($res) > 0) {
           $rtn_arr['_state']  = 'error';
           $rtn_arr['_msg']    = '当前部门还有下级部门，请先删除下级部门再删除!';
           echo json_encode($rtn_arr);
           exit;
        }
        
        $p_a_list   = $model->get_part_admin_list($del_id);
        if ($p_a_list) {
            $rtn_arr['_state']  = 'error';
            $rtn_arr['_msg']    = '部门下面还有相关的人员，请先移除部门下的人员!';
            echo json_encode($rtn_arr);
            exit;
        }
        
        $admin_ses  = Yii::$app->session['admin_info'];
        if ($admin_ses['powers'] != 'all' && $admin_ses['is_owner'] != 1) { //即不是管理员，也不是部门负责人，不能修改部门数据
            $rtn_arr['_state']  = 'error';
            $rtn_arr['_msg']    = '当前账号暂时无权限!';
            echo json_encode($rtn_arr);
            exit;
        }
        
        if ($admin_ses['powers'] == 'all') {
            $tmp    = Department::findOne($del_id);
            $tmp->delete();
            yii::$app->helper->adminlog($del_id,
                [
                    'action'    => '删除',
                    'model'     => $tmp,
                ],'app\models\DepartmentLog');
        } else {
            $ad_low = $model->get_part_low_list($admin_ses['department_id']);
            if (in_array($del_id,$ad_low)) {
                $tmp    = Department::findOne($del_id);
                $tmp->delete();
                yii::$app->helper->adminlog($del_id,
                    [
                        'action'    => '删除',
                        'model'     => $tmp,
                    ],'app\models\DepartmentLog');
            } else {
                $rtn_arr['_state']  = 'error';
                $rtn_arr['_msg']    = '你暂时没有删除此部门的权限!';
                echo json_encode($rtn_arr);
                exit;
            }
        }
        $rtn_arr['_state']  = 'ok';
        $rtn_arr['_msg']    = '删除成功!';
        echo json_encode($rtn_arr);
    }
    
    public function actionLoglist()
    {
        $DpLog      = new \app\models\DepartmentLog();
        $count      = $DpLog->find()->count();
        $pageSize   = yii::$app->request->getQueryParam('pagesize');
        $pageSize   = empty($pageSize) ? 10 : intval($pageSize);
        $pages      = new Pagination(['totalCount' => $count, 'defaultPageSize' => $pageSize]);
        $logList    = $DpLog->find()->limit($pages->limit)->offset($pages->offset)->orderBy('id desc')->all();
        return $this->render('loglist', ['logs'=>$logList,'pages'=>$pages]);
    }
}
